import type { App } from 'vue'
import {
  createRouter,
  createWebHashHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw
} from 'vue-router'
import { useWorktabStore } from '@/store/modules/worktab'
import Home from '@views/index/index.vue'
import { SystemInfo } from '@/config/setting'
import { useUserStore } from '@/store/modules/user'
import { menuService } from '@/api/menuApi'
import { getIframeRoutes, routerMatch } from '@/utils/menu'
import { useMenuStore } from '@/store/modules/menu'
import { useSettingStore } from '@/store/modules/setting'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { isIframe } from '@/utils/utils'

// 创建路由守卫参数类型别名
type GuardParams = {
  to: RouteLocationNormalized
  next: NavigationGuardNext
}

// 顶部进度条配置
NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 600, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  parent: 'body' //指定进度条的父容器
})

// 路由项扩展
export type AppRouteRecordRaw = RouteRecordRaw & {
  hidden?: boolean
}

// 首页
export const HOME_PAGE = '/dashboard/console'

// 不需要权限的路由
const routes = [
  {
    path: '/',
    redirect: HOME_PAGE
  },
  {
    path: '/dashboard',
    component: Home,
    meta: {
      title: '监控中心',
      title_en: 'Dashboard'
    },
    children: [
      {
        path: '/dashboard/console',
        name: 'Console',
        component: () => import(`@views/dashboard/console/index.vue`),
        meta: {
          title: '工作台',
          title_en: 'Workbench',
          keepAlive: false
        }
      },
      {
        path: '/dashboard/analysis',
        name: 'Analysis',
        component: () => import(`@views/dashboard/analysis/index.vue`),
        meta: {
          title: '分析页',
          title_en: 'Analysis',
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@views/login/index.vue'),
    meta: {
      title: '登录',
      isHideTab: true,
      setTheme: true
    }
  },
  {
    path: '/register',
    component: () => import('@views/register/index.vue'),
    meta: {
      title: '注册',
      isHideTab: true,
      noLogin: true,
      setTheme: true
    }
  },
  {
    path: '/forget-password',
    component: () => import('@views/forget-password/index.vue'),
    meta: {
      title: '忘记密码',
      isHideTab: true,
      noLogin: true,
      setTheme: true
    }
  },
  {
    path: '/exception',
    component: Home,
    meta: {
      title: '异常页面',
      title_en: 'Exception'
    },
    children: [
      {
        path: '/exception/403',
        component: () => import('@/views/exception/403.vue'),
        meta: {
          title: '403',
          title_en: '403'
        }
      },
      {
        path: '/exception/404',
        component: () => import('@views/exception/404.vue'),
        meta: {
          title: '404',
          title_en: '404'
        }
      },
      {
        path: '/exception/500',
        component: () => import('@views/exception/500.vue'),
        meta: {
          title: '500',
          title_en: '500'
        }
      }
    ]
  },
  {
    path: '/outside',
    component: Home,
    meta: {
      title: '内嵌页面',
      title_en: 'Outside'
    },
    children: [
      {
        path: '/outside/iframe/:path',
        component: () => import('@/views/outside/Iframe.vue'),
        meta: {
          title: 'iframe',
          title_en: 'iframe'
        }
      }
    ]
  },
  {
    path: '/template/pricing',
    component: () => import('@views/template/pricing.vue'),
    meta: {
      title: '定价',
      isHideTab: true
    }
  }
] as AppRouteRecordRaw[]

export const router = createRouter({
  history: createWebHashHistory(), // history 模式
  routes: routes, // 路由表
  scrollBehavior: () => ({ left: 0, top: 0 }) // 页面滚动行为
})

// 需要权限的路由
export const roleRoutes: AppRouteRecordRaw[] = [
  {
    path: '/appUser',
    name: 'AppUser',
    component: Home,
    meta: {
      title: 'App用户管理',
      title_en: 'App User Management',
      icon: '&#xe7ae;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/appUser/user',
        name: 'AppUserList',
        component: () => import('@views/appUser/user/User.vue'),
        meta: {
          title: 'App用户列表',
          title_en: 'App User List',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/user/userInfo',
        name: 'AppUserInfo',
        component: () => import('@views/appUser/user/userInfo/index.vue'),
        meta: {
          title: 'App用户信息',
          title_en: 'App User Info',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/user/water',
        name: 'AppUserWater',
        component: () => import('@views/appUser/user/water/index.vue'),
        meta: {
          title: 'App用户封禁管理',
          title_en: 'App User Wallet Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/IM/report',
        name: 'AppUserIMReport',
        component: () => import('@views/appUser/IM/report/index.vue'),
        meta: {
          title: 'IM举报管理',
          title_en: 'App User IM Report',
          isHide: false,
          keepAlive: false
        }
      },

      {
        path: '/bussinessUser/IM/report',
        name: 'BussinessUserIMReport',
        component: () => import('@views/bussinessUser/IM/report/index.vue'),
        meta: {
          title: 'IM举报管理',
          title_en: 'BussinessUserIMReport',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/comment/commentSys',
        name: 'BussinessUserComment',
        component: () => import('@views/bussinessUser/comment/commentSys/index.vue'),
        meta: {
          title: '用户评论管理',
          title_en: 'BussinessUserComment',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/bussiness/bussinessList',
        name: 'businessList',
        component: () => import('@views/bussinessUser/bussiness/bussinessList/index.vue'),
        meta: {
          title: '商家列表',
          title_en: 'businessList',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/bussiness/settlement',
        name: 'settlement',
        component: () => import('@views/bussinessUser/bussiness/settlement/index.vue'),
        meta: {
          title: '入驻管理',
          title_en: 'settlement',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/renovation/commoditySystem',
        name: 'commoditySystem',
        component: () => import('@views/bussinessUser/renovation/commoditySystem/index.vue'),
        meta: {
          title: '商品管理',
          title_en: 'commoditySystem',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/renovation/commdityClass',
        name: 'commdityClass',
        component: () => import('@views/bussinessUser/renovation/commdityClass/index.vue'),
        meta: {
          title: '商品类别',
          title_en: 'commdityClass',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/bussinessUser/renovation/brand',
        name: 'brand',
        component: () => import('@views/bussinessUser/renovation/brand/index.vue'),
        meta: {
          title: '品牌管理',
          title_en: 'brand',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/user/manage',
        name: 'AppUserManage',
        component: () => import('@views/appUser/user/manage/index.vue'),
        meta: {
          title: 'App用户管理',
          title_en: 'App User Manage',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/content/manage',
        name: 'AppUserContentManage',
        component: () => import('@views/appUser/content/manage/index.vue'),
        meta: {
          title: 'App内容管理',
          title_en: 'App Content Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/content/classify',
        name: 'AppUserContentClassify',
        component: () => import('@views/appUser/content/classify/index.vue'),
        meta: {
          title: 'App内容分类',
          title_en: 'App Content Classification',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/order/pending',
        name: 'AppUserOrderPending',
        component: () => import('@views/appUser/order/pending/index.vue'),
        meta: {
          title: 'App订单待处理',
          title_en: 'App Order Pending',
          isHide: false,
          keepAlive: false
        }
      },
         {
        path: '/appUser/order/after',
        name: 'AppUserOrderAfter',
        component: () => import('@views/appUser/order/after/index.vue'),
        meta: {
          title: 'App订单已处理',
          title_en: 'App Order After',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/risk/IPBlacklist',
        name: 'AppUserRiskIPBlacklist',
        component: () => import('@views/appUser/risk/IPBlacklist/index.vue'),
        meta: {
          title: 'AppIP黑名单',
          title_en: 'App IP Blacklist',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/comment/commentSys',
        name: 'AppUserCommentCommentSys',
        component: () => import('@views/appUser/comment/commentSys/index.vue'),
        meta: {
          title: 'App评论管理',
          title_en: 'App Comment Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/appUser/comment/trends',
        name: 'AppUserCommentTrends',
        component: () => import('@views/appUser/comment/trends/index.vue'),
        meta: {
          title: '宠圈动态评论',
          title_en: 'Pet Circle Trends Comments',
          isHide: false,
          keepAlive: false
        }
      }
         ,{
        path: '/appUser/content/reportInfo',
        name: 'AppUserReportReportInfo',
        component: () => import('@views/appUser/content/reportInfo/index.vue'),
        meta: {
          title: 'App举报信息',
          title_en: 'App Report Information',
          isHide: false,
          keepAlive: false
        }
      },
         {
        path: '/appUser/renovation/commdityClass',
        name: 'AppUserRenovationCommdityClass',
        component: () => import('@views/appUser/renovation/commdityClass/index.vue'),
        meta: {
          title: 'App商品系统',
          title_en: 'App Commodity System',
          isHide: false,
          keepAlive: false
        }
      },
       {
        path: '/setup/history/manage',
        name: 'AppUserHistoryManage',
        component: () => import('@views/setup/history/manage/index.vue'),
        meta: {
          title: 'App历史管理',
          title_en: 'App History Management',
          isHide: false,
          keepAlive: false
        }
      }

    ]
  },
  {
    path: '/user',
    name: 'User',
    component: Home,
    meta: {
      title: '用户管理'
    },
    children: [
      {
        path: '/user/user',
        name: 'Users',
        component: () => import('@views/user/User.vue'),
        meta: {
          title: '个人中心'
        }
      },
      {
        path: '/user/account',
        name: 'Account',
        component: () => import('@views/user/Account.vue'),
        meta: {
          title: '账号管理'
        }
      },
      {
        path: '/user/department',
        name: 'Department',
        component: () => import('@views/user/Department.vue'),
        meta: {
          title: '部门管理'
        }
      },
      {
        path: '/user/role',
        name: 'Role',
        component: () => import('@views/user/Role.vue'),
        meta: {
          title: '角色权限'
        }
      },
      {
        path: '/user/manage',
        name: 'UserManage',
        component: () => import('@views/user/manage/index.vue'),
        meta: {
          title: '用户管理'
        }
      },
      {
        path: '/user/userInfo',
        name: 'UserInfo',
        component: () => import('@views/user/userInfo/index.vue'),
        meta: {
          title: '用户信息管理'
        }
      },
      {
        path: '/user/water',
        name: 'UserWater',
        component: () => import('@views/user/water/index.vue'),
        meta: {
          title: '钱包管理'
        }
      }
    ]
  },
  {
    path: '/system',
    name: 'System',
    component: Home,
    meta: {
      title: '系统管理',
      title_en: 'System Management',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/setup/dict',
        component: () => import('@views/setup/dict/index.vue'),
        meta: {
          title: '字典管理',
          title_en: 'Dict Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/config',
        component: () => import('@views/setup/config/index.vue'),
        meta: {
          title: '参数配置',
          title_en: 'Config Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/sos',
        component: () => import('@views/sos/index.vue'),
        meta: {
          title: '一键急救配置',
          title_en: 'Dict Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/role',
        component: () => import('@views/setup/role/index.vue'),
        meta: {
          title: '角色管理',
          title_en: 'Role Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/user',
        component: () => import('@views/setup/user/index.vue'),
        meta: {
          title: '用户管理',
          title_en: 'User Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/tabs',
        component: () => import('@views/setup/tabs/index.vue'),
        meta: {
          title: '菜单管理',
          title_en: 'Menu Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/businessMenus',
        component: () => import('@views/setup/businessMenus/index.vue'),
        meta: {
          title: '商家菜单',
          title_en: 'Business Menu',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/setup/phone',
        component: () => import('@views/setup/phone/index.vue'),
        meta: {
          title: '手机号管理',
          title_en: 'Phone Management',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/comment',
    name: 'Comment',
    component: Home,
    meta: {
      title: '评论管理',
      title_en: 'Comment Management',
      icon: '&#xe8f0;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/comment/commentSys',
        component: () => import('@views/comment/commentSys/index.vue'),
        meta: {
          title: '评论管理',
          title_en: 'Comment Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/comment/keyword',
        component: () => import('@views/comment/keyword/index.vue'),
        meta: {
          title: '关键词管理',
          title_en: 'keyword Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/comment/sensitive',
        component: () => import('@views/comment/sensitive/index.vue'),
        meta: {
          title: '敏感词管理',
          title_en: 'Sensitive Word Management',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/content',
    name: 'Content',
    component: Home,
    meta: {
      title: '内容管理',
      title_en: 'Content Management',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/content/classify',
        component: () => import('@views/content/classify/index.vue'),
        meta: {
          title: '内容分类',
          title_en: 'Content Classification',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/content/manage',
        component: () => import('@views/content/manage/index.vue'),
        meta: {
          title: '动态管理',
          title_en: 'Dynamic Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/content/control',
        component: () => import('@views/content/control/index.vue'),
        meta: {
          title: '内容风控',
          title_en: 'Content Risk Control',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/risk',
    name: 'Risk',
    component: Home,
    meta: {
      title: '风控管理',
      title_en: 'Risk Management',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/risk/IPBlacklist',
        component: () => import('@views/risk/IPBlacklist/index.vue'),
        meta: {
          title: 'IP黑名单',
          title_en: 'IP Blacklist',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/risk/userBlackList',
        component: () => import('@views/risk/userBlacklist/index.vue'),
        meta: {
          title: '用户黑名单',
          title_en: 'User Blacklist',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/risk/riskRules',
        component: () => import('@views/risk/riskRules/index.vue'),
        meta: {
          title: '风险规则',
          title_en: 'Risk Rules',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/renovation',
    name: 'Renovation',
    component: Home,
    meta: {
      title: '商品管理',
      title_en: 'Goods Management'
    },
    children: [
      {
        path: '/renovation/commoditySystem',
        component: () => import('@views/renovation/commoditySystem/index.vue'),
        meta: {
          title: '商品管理',
          title_en: 'Commodity Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/renovation/commdityClass',
        component: () => import('@views/renovation/commdityClass/index.vue'),
        meta: {
          title: '商品类别',
          title_en: 'Commodity Class',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/renovation/brand',
        component: () => import('@views/renovation/brand/index.vue'),
        meta: {
          title: '品牌管理',
          title_en: 'Brand Management',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/two',
    name: 'Two',
    component: Home,
    meta: {
      titile: '二次认证管理',
      title_en: 'Two-factor Authentication Management'
    },
    children: [
      {
        path: '/setup/privacy',
        component: () => import('@views/setup/privacy/index.vue'),
        meta: {
          title: '二次认证',
          title_en: 'Two-factor Authentication',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/menu',
    name: 'Menu',
    component: Home,
    meta: {
      title: '菜单管理',
      title_en: 'Menu Management'
    },
    children: [
      {
        path: '/menu/menu',
        name: 'Menus',
        component: () => import('@views/menu/Menu.vue'),
        meta: {
          title: '菜单管理',
          title_en: 'Menu Management'
        }
      },
      {
        path: '/menu/permission',
        name: 'Permission',
        component: () => import('@views/menu/Permission.vue'),
        meta: {
          title: '权限控制',
          title_en: 'Permission Control'
        }
      },
      {
        path: '/menu/nested',
        name: 'Nested',
        meta: {
          title: '嵌套菜单',
          title_en: 'Nested Menu'
        },
        children: [
          {
            path: '/menu/nested/menu1',
            name: 'NestedMenu1',
            component: () => import('@views/menu/nested/menu1.vue'),
            meta: {
              title: '菜单1',
              title_en: 'Menu 1'
            }
          },
          {
            path: '/menu/nested/menu2',
            name: 'NestedMenu2',
            meta: {
              title: '菜单2',
              title_en: 'Menu 2'
            },
            children: [
              {
                path: '/menu/nested/menu2/menu2-1',
                name: 'NestedMenu2-1',
                component: () => import('@views/menu/nested/menu2/menu2-1.vue'),
                meta: {
                  title: '菜单2-1',
                  title_en: 'Menu 2-1'
                }
              }
            ]
          },
          {
            path: '/menu/nested/menu3',
            name: 'NestedMenu3',
            meta: {
              title: '菜单3',
              title_en: 'Menu 3'
            },
            children: [
              {
                path: '/menu/nested/menu3/menu3-1',
                name: 'NestedMenu3-1',
                component: () => import('@views/menu/nested/menu3/menu3-1.vue'),
                meta: {
                  title: '菜单3-1',
                  title_en: 'Menu 3-1'
                }
              },
              {
                path: '/menu/nested/menu3/menu3-2',
                name: 'NestedMenu3-2',
                meta: {
                  title: '菜单3-2',
                  title_en: 'Menu 3-2'
                },
                children: [
                  {
                    path: '/menu/nested/menu3/menu3-2/menu3-2-1',
                    name: 'NestedMenu3-2-1',
                    component: () => import('@views/menu/nested/menu3/menu3-2/menu3-2-1.vue'),
                    meta: {
                      title: '菜单3-2-1',
                      title_en: 'Menu 3-2-1'
                    }
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/result',
    name: 'Result',
    component: Home,
    meta: {
      title: '结果页面'
    },
    children: [
      {
        path: '/result/success',
        name: 'Success',
        component: () => import('@views/result/Success.vue'),
        meta: {
          title: '成功页'
        }
      },
      {
        path: '/result/fail',
        name: 'Fail',
        component: () => import('@views/result/Fail.vue'),
        meta: {
          title: '失败页'
        }
      }
    ]
  },

  {
    path: '/member',
    name: 'Member',
    component: Home,
    meta: {
      title: '会员管理',
      title_en: 'Member Management',
      icon: '&#xe601;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/member/memberList',
        name: 'MemberList',
        component: () => import('@views/member/memberList/index.vue'),
        meta: {
          title: '会员列表',
          title_en: 'Member List',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/member/levelList',
        name: 'MemberLevel',
        component: () => import('@views/member/levelList/index.vue'),
        meta: {
          title: '会员等级',
          title_en: 'Member Level',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/member/equity',
        name: 'MemberEquity',
        component: () => import('@views/member/equity/index.vue'),
        meta: {
          title: '会员权益',
          title_en: 'Member Equity',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/member/tips',
        name: 'MemberTag',
        component: () => import('@views/member/tips/index.vue'),
        meta: {
          title: '会员标签',
          title_en: 'Member Tag',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    // 订单管理
    name: 'Order',
    path: '/order',
    component: Home,
    meta: {
      title: '订单管理',
      title_en: 'Order Management',
      icon: '&#xe860;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        name: 'Pending',
        path: '/order/pending',
        component: () => import('@views/order/pending/index.vue'),
        meta: {
          title: '待处理订单',
          title_en: 'Pending Orders',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'After',
        path: '/order/after',
        component: () => import('@views/order/after/index.vue'),
        meta: {
          title: '已完成订单',
          title_en: 'Completed Orders',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    // 活动管理
    name: 'Active',
    path: '/active',
    component: Home,
    meta: {
      title: '活动管理',
      title_en: 'Activity Management',
      icon: '&#xe860;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        name: 'ActiveList',
        path: '/active/list',
        component: () => import('@views/active/index.vue'),
        meta: {
          title: '活动列表',
          title_en: 'Activity List',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'ActiveDetails',
        path: '/active/details',
        component: () => import('@views/active/activeDetails.vue'),
        meta: {
          title: '活动详情',
          title_en: 'Activity Details',
          isHide: true,
          keepAlive: false
        }
      },
      {
        name: 'CouponList',
        path: '/active/couponlist',
        component: () => import('@views/active/couponlist/index.vue'),
        meta: {
          title: '优惠券列表',
          title_en: 'Coupon List',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'DiscountList',
        path: '/active/discountlist',
        component: () => import('@views/active/discountlist/index.vue'),
        meta: {
          title: '折扣活动',
          title_en: 'Discount Activity',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'SeckillList',
        path: '/active/seckilllist',
        component: () => import('@views/active/seckilllist/index.vue'),
        meta: {
          title: '秒杀活动',
          title_en: 'Seckill Activity',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'PoliteList',
        path: '/active/politelist',
        component: () => import('@views/active/politelist/index.vue'),
        meta: {
          title: '白名单',
          title_en: 'Whitelist',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/business',
    name: 'Business',
    component: Home,
    meta: {
      title: '商家管理',
      title_en: 'Business Management',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        name: 'BusinessList',
        path: '/business/businessList',
        component: () => import('@views/business/businessList/index.vue'),
        meta: {
          title: '商家列表',
          title_en: 'Business List',
          isHide: false,
          keepAlive: false
        }
      },
      {
        name: 'Settlement',
        path: '/business/settlement',
        component: () => import('@views/business/settlement/index.vue'),
        meta: {
          title: '入驻申请',
          title_en: 'Settlement',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/finance',
    name: 'Finance',
    component: Home,
    meta: {
      title: '财务管理',
      title_en: 'Financial Management',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/finance/application',
        name: 'Application',
        component: () => import('@/views/finance/application/index.vue'),
        meta: {
          title: '用户提现申请',
          title_en: 'Finance Application',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/finance/withdrawal',
        name: 'Withdrawal',
        component: () => import('@/views/finance/withdrawal/index.vue'),
        meta: {
          title: '提现申请',
          title_en: 'Withdrawal',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/finance/bond',
        name: 'Bond',
        component: () => import('@/views/finance/bond/index.vue'),
        meta: {
          title: '保证金',
          title_en: 'Bond',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/finance/overview',
        name: 'Overview',
        component: () => import('@/views/finance/overview/index.vue'),
        meta: {
          title: '财务概况',
          title_en: 'Finance Overview',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/notice',
    component: Home,
    name: 'Notice',
    meta: {
      title: '消息中心',
      title_en: 'Message Center',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/notice/history',
        name: 'History',
        component: () => import('@/views/notice/history.vue'),
        meta: {
          title: '历史消息',
          title_en: 'History Message',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/notice/push',
        name: 'Push',
        component: () => import('@/views/notice/push.vue'),
        meta: {
          title: '消息推送',
          title_en: 'Message Push',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/version',
    name: 'Version',
    component: Home,
    meta: {
      title: '版本管理',
      title_en: 'Version Management',
      icon: '&#xe8f0;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/version/appInfo',
        component: () => import('@views/version/appInfo/index.vue'),
        meta: {
          title: '版本管理',
          title_en: 'Agreement Management',
          isHide: false,
          keepAlive: false
        }
      },
      {
        path: '/version/agrementInfo',
        component: () => import('@views/version/agrementInfo/index.vue'),
        meta: {
          title: '协议管理',
          title_en: 'Agreement Details',
          isHide: false,
          keepAlive: false
        }

      }
    ]
  },
  {
    path: '/report',
    name: 'Report',
    component: Home,
    meta: {
      title: '举报管理',
      title_en: 'Report Management',
      icon: '&#xe8f0;',
      isHide: false,
      keepAlive: false
    },
    children: [
      {
        path: '/report/reportInfo',
        name: 'ReportInfo',
        component: () => import('@views/report/reportInfo/index.vue'),
        meta: {
          title: '举报信息',
          title_en: 'Report Info',
          isHide: false,
          keepAlive: false
        }
      }
    ]
  }
] as AppRouteRecordRaw[]

// 是否注册路由
const isRouteRegistered = ref(false)

// 路由跳转前
router.beforeEach(async (to, from, next) => {
  // 显示顶部进度条
  if (useSettingStore().showNprogress) {
    NProgress.start()
  }

  // 设置登录注册页面主题
  setSystemTheme(to)

  // 检查是否登录或者不需要登录
  const loginChecked = checkLogin({ to, next })
  if (loginChecked) {
    return
  }

  // 获取菜单数据，动态注册路由
  if (await handleRegisterRoutes({ to, next })) {
    return
  }

  console.log('所有路由:', router.getRoutes())
  console.log('目标路由路径:', to.path)
  console.log('目标路由:', JSON.stringify(to, null, 2))

  // 检查路由是否存在
  const routeExists = checkRouteExist({ to, next })
  if (routeExists) {
    return
  }

  // 设置标签页
  setWorktab(to)

  // 设置页面标题
  setPageTitle(to)
  next()
})

// 路由跳转完成
router.afterEach(() => {
  // 隐藏顶部进度条
  if (useSettingStore().showNprogress) {
    NProgress.done()
  }
})

// 设置标签页
function setWorktab(to: RouteLocationNormalized) {
  const worktabStore = useWorktabStore()
  const settingStore = useSettingStore()
  const { meta, path, params, query } = to
  const { title, title_en, isHideTab } = meta

  if (!isHideTab) {
    if (isIframe(path)) {
      const iframeRoute = getIframeRoutes().find((route: any) => route.path === to.path)

      if (iframeRoute?.meta) {
        const { title, title_en } = iframeRoute.meta
        worktabStore.router({
          title,
          title_en,
          path,
          params,
          query
        })
      }
    } else {
      if (settingStore.showWorkTab || path === HOME_PAGE) {
        worktabStore.router({
          title: title as string,
          title_en: title_en as string,
          path,
          params,
          query
        })
      }
    }
  }
}

import { useTheme } from '@/composables/useTheme'

// 设置登录注册页面主题
function setSystemTheme(to: RouteLocationNormalized) {
  if (to.meta.setTheme) {
    useTheme().switchTheme(useSettingStore().systemThemeType)
  }
}

// 检查路由是否登录或不需要登录
function checkLogin({ to, next }: GuardParams) {
  const userStore = useUserStore()
  const { meta, path } = to
  const { noLogin } = meta

  if (!userStore.isLogin && path !== '/login' && !noLogin) {
    userStore.logOut()
    next('/login')
    return true
  }
  return false
}

// 检查路由是否存在
function checkRouteExist({ to, next }: GuardParams) {
  if (to.matched.length === 0) {
    next('/exception/404')
    return true
  }
  return false
}

// 设置页面标题
function setPageTitle(to: RouteLocationNormalized) {
  const { meta } = to

  if (meta.title) {
    if (meta.title === 'iframe') {
      const title2 = to.path.split('/').pop()
      const decodeTitle = decodeURIComponent(title2 || '')
      document.title = `${decodeTitle} - ${SystemInfo.name}`
    } else {
      document.title = `${meta.title} - ${SystemInfo.name}`
    }
  }
}

// 处理路由注册
async function handleRegisterRoutes({ to, next }: GuardParams) {
  const userStore = useUserStore()

  // 检查当前用户是否与上次注册路由时的用户相同
  const currentUserId = userStore.info?.id
  const lastRegisteredUserId = (window as any).lastRegisteredUserId

  // 如果用户ID不同，说明切换了账号，需要重新注册路由
  const shouldReRegister = currentUserId && currentUserId !== lastRegisteredUserId

  // 如果用户已登录且路由未注册，或者需要重新注册，则注册路由
  if ((!isRouteRegistered.value || shouldReRegister) && userStore.isLogin) {
    try {
      await registerRoutes()
      // 记录当前用户ID
      if (currentUserId) {
        (window as any).lastRegisteredUserId = currentUserId
      }
      next({ ...to, replace: true })
    } catch (error) {
      console.error('Failed to register routes:', error)
      // 检查是否已经在异常页面，避免无限重定向
      if (to.path !== '/exception/500') {
        next('/exception/500')
      } else {
        // 如果已经在异常页面，则直接允许导航
        next()
      }
    }
    return true
  }

  return false
}

// 获取菜单，注册路由
async function registerRoutes(): Promise<void> {
  try {
    // 获取菜单列表
    const { menuList, closeLoading } = await menuService.getMenuList()

    // 添加调试日志，查看获取到的菜单列表
    console.log('获取到的菜单列表:', JSON.stringify(menuList, null, 2))

    // 定义默认菜单，作为最后的兜底方案
    const defaultMenuList = [
      {
        // 仪表盘路由
        id: 1,
        name: 'dashboard',
        path: '/dashboard',
        meta: {
          title: '仪表盘',
          title_en: 'Dashboard',
          icon: '&#xe721;',
          isHide: false,
          keepAlive: false
        },
        children: [
          {
            id: 101,
            name: 'Console',
            path: '/dashboard/console',
            meta: {
              title: '工作台',
              title_en: 'Workbench',
              isHide: false,
              keepAlive: false
            }
          }
        ]
      }
    ]

    // 如果从服务器获取的菜单列表为空或无效，则使用默认菜单列表
    const finalMenuList =
      Array.isArray(menuList) && menuList.length > 0 ? menuList : defaultMenuList

    console.log('处理后的菜单列表:', JSON.stringify(menuList, null, 2))
    console.log('默认菜单列表:', JSON.stringify(defaultMenuList, null, 2))
    console.log('最终使用的菜单列表:', JSON.stringify(finalMenuList, null, 2))

    // 菜单列表存储到 pinia
    useMenuStore().setMenuList(finalMenuList as [])
    // 注册路由
    routerMatch(finalMenuList, roleRoutes)
    // 注册完成
    isRouteRegistered.value = true
    // 关闭 loading
    closeLoading()
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    throw error
  }
}

export function initRouter(app: App<Element>) {
  app.use(router)
}
